// components/home/home.js
const httprequest = require('../../../utils/http_utils.js')
const dateutil = require('../../../utils/date_util.js')
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    menulist: [
      // {
      //   name: '设备信息',
      //   icon: 'iconshebeixinxi'
      // },
      // {
      //   name: '扫一扫',
      //   icon: 'iconsaoyisao'
      // },
      // {
      //   name: '报修',
      //   icon: 'iconxunjianchulirenyuan'
      // },
      // {
      //   name: '报警',
      //   icon: 'iconbaojing'
      // },
      // {
      //   name: '日常巡检',
      //   icon: 'iconrichangxunjian'
      // },
      // {
      //   name: '维护保养',
      //   icon: 'iconguzhangweihu'
      // },
      // {
      //   name: '日常保洁',
      //   icon: 'iconrichangbaoji01'
      // },
      // {
      //   name: '设备监测',
      //   icon: 'iconshishijiance'
      // }
    ],
    WorkOrderList: [], //工单列表
    info: '', //提示信息
    pageSize: 15, //每页显示条数
    counter: 1, //计数器
    pageStart: 0, //开始数据条数
    totalNum: 0, //总条数
    uploading: false,
    downloading: false,
    noMore: false,
    loadingFailed: false,
    title: '兰生大厦',
    showzanwu: false,
    taskHight: false, //我的任务高度值
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function() {
      this.getMenulist();
      // this.getWorkOrderList();
      this.refreshView = this.selectComponent("#refreshView")
    },
  },

  pageLifetimes: {
    show: function() {
      this.setData({
        WorkOrderList: []
      })
      this.getWorkOrderList();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //临时跳转
    linshi: function(){
      wx.navigateTo({
        url: '../Maintenance/Maintenance',
      })
    },

    getMenulist: function() {
      var menu_list = [];
      var storage_list = wx.getStorageSync('UserInfo').AppLogin.AppModuleDTO.filter(function(item) {
        return item.ParentGuid === "222222222222222222222222222222222222";
      })
      if (storage_list.length < 5){
        this.setData({
          taskHight:true
        })
      }else{
        this.setData({
          taskHight: false
        })
      }
      for (var i = 0; i < storage_list.length; i++) {
        var param = {
          RowGuid: storage_list[i].RowGuid,
          Name: storage_list[i].ModuleName,
          Icon: storage_list[i].BigIconAddress,
          ModuleUrl: storage_list[i].ModuleUrl
        }
        menu_list.push(param)
      }
      //根据RowGuid去重
      const RowGuid = 'RowGuid';
      menu_list = menu_list.reduce((all, next) => all.some((atom) => atom[RowGuid] == next[RowGuid]) ? all : [...all, next], []);
      this.setData({
        menulist: menu_list
      })
      console.log('menulist---', this.data.menulist)
    },

    onPullDownRefresh: function() { //调用index页面生命周期
      this.triggerEvent("action");
    },
    stop: function() {
      var that = this
      setTimeout(() => {
        that.setData({
          uploading: true,
          noMore: false,
          counter: 1,
          WorkOrderList: []
        })
        that.getWorkOrderList();
        that.refreshView.stopPullRefresh()
      }, 1000)
    },
    click: function(e) {
      wx.navigateTo({
        url: '../details/details?RowGuid=' + e.currentTarget.dataset.rowguid
      })
    },
    tiaozhuan(e) { //页面跳转
      var rowguid = e.currentTarget.dataset.rowguid; //获取菜单rowguid
      var url = e.currentTarget.dataset.url; //获取按钮跳转地址
      if (url.indexOf('saoyisao') == -1) {
        // if (url == '/pages/alarm/alarm'){
        //   if (wx.getStorageSync('UserInfo').AppLogin.AlarmType == "" || wx.getStorageSync('UserInfo').AppLogin.AlarmType == null || wx.getStorageSync('UserInfo').AppLogin.AlarmType == undefined){
        //     this.setData({
        //       info: '当前用户暂无查看报警信息权限！'
        //     })
        //   } else {
        //     wx.navigateTo({
        //       url: url + '?ParentGuid=' + rowguid,
        //     })
        //   }
        // }else{
          console.log(url+"--------------------------------首页跳转")
          wx.navigateTo({
            url: url + '?ParentGuid=' + rowguid,
          })
        // }
      } else {
        this.scancode();
      }

    },

    //扫一扫
    scancode: function() {
      var that = this
      wx.scanCode({
        success: function(res) {
          console.log(res)
          if (res.result != null && res.result != '') {
            var params = {
              TabNo: 0,
              EquipmentCode: res.result,
              RowGuid: ''
            };
            httprequest.PostValidateRequest(httprequest.apiInfo.Project_GetEquipDetailMobileApi, params,
              function(res2) {
                console.log(res2)
                if (res2.Data.equipDatailData.length > 0) {
                  wx.navigateTo({
                    url: '/pages/equip_detail/equip_detail?EquipmentCode=' + res.result
                  })
                } else {
                  that.setData({
                    info: '暂无设备信息'
                  })
                }
              },
              function(err) {
                that.setData({
                  info: '暂无设备信息'
                })
              })
          } else {
            this.setData({
              info: '未扫描到信息'
            })
          }
        },
        fail: function(err) {
          this.setData({
            info: '照相机打开失败！'
          })
        }
      })
    },
    tabChange(e) {
      if (e.detail.index == 0) {
        wx.redirectTo({
          url: '../home/home',
        })
      } else if (e.detail.index == 1) {
        wx.redirectTo({
          url: '../contact/contact',
        })
      } else {
        wx.redirectTo({
          url: '../person/person',
        })
      }
    },
    //获取工单列表
    getWorkOrderList: function() {
      var that = this
      console.log(wx.getStorageSync('UserInfo').AppLogin.ProjectCode + '------')
      var Flag = true;
      var CoditionArray = new Array();
      var params = {
        rolename: '*',
        pagesize: that.data.pageSize,
        currentpage: that.data.counter,
        where: JSON.stringify(CoditionArray),
        orderby: 'order by WorkTime desc',
        type: 2
      }
      console.log(JSON.stringify(params)+"------首页我的任务")
      httprequest.GetValidateRequest(httprequest.apiInfo.GetWorkOrderSearch2Api, params,
        function(res) {
          console.log("resresres", res)
          if (res.totalNum == 0 || res.flag == '暂无数据！') {
            that.setData({
              showzanwu: true
            })
          } else {
            that.setData({
              totalNum: res.totalNum,
              showzanwu: false
            })
            var datalist = new Array();
            datalist = that.data.WorkOrderList
            console.log("datalist", JSON.stringify(datalist))
            //过滤时间
            for (var i = 0; i < JSON.parse(res.pageData).length; i++) {
              // var WorkOrderStateText = 'WorkOrderList[' + i + '].WorkOrderStateText';
              // var Description = 'WorkOrderList[' + i + '].Description';
              // var WorkTime = 'WorkOrderList[' + i + '].WorkTime';
              // var RowGuid = 'WorkOrderList[' + i + '].RowGuid';
              // that.setData({
              //   [WorkOrderStateText]: JSON.parse(res.pageData)[i].WorkOrderStateText,
              //   [Description]: JSON.parse(res.pageData)[i].Description,
              //   [RowGuid]: JSON.parse(res.pageData)[i].RowGuid,
              //   [WorkTime]: dateutil.formatTime(JSON.parse(res.pageData)[i].WorkTime)
              // })
              var param = {
                WorkOrderStateText: JSON.parse(res.pageData)[i].WorkOrderStateText,
                Description: JSON.parse(res.pageData)[i].Description,
                RowGuid: JSON.parse(res.pageData)[i].RowGuid,
                WorkTime: dateutil.formatTime(JSON.parse(res.pageData)[i].WorkTime)
              }
              datalist.push(param)
            }
            console.log("newlist", JSON.stringify(datalist))
            that.setData({
              WorkOrderList: datalist
            })
          }
          that.setData({
            uploading: false,
            downloading: false,
          })
        },
        function(err) {
          console.error(err)
        })
    },
    //上拉
    scrollToLower: function() {
      console.log("scrollToLower")
      var that = this
      var pages = Math.round((that.data.totalNum / that.data.pageSize) * 100) / 100
      if (that.data.counter > pages) {
        that.setData({
          noMore: true
        })
      } else {
        that.setData({
          noMore: false,
          downloading: true
        })
        that.setData({
          counter: that.data.counter + 1
        })
        that.getWorkOrderList();
      }
    },
    //下拉
    // scrollToUpper: function() {
    //   console.log("scrollToUpper")
    //   var that = this
    //   that.setData({
    //     uploading: true,
    //     noMore: false,
    //     counter: 1,
    //     WorkOrderList: []
    //   })
    //   that.getWorkOrderList();
    // },

    //触摸开始
    handletouchstart: function(event) {
      this.refreshView.handletouchstart(event)
    },
    //触摸移动
    handletouchmove: function(event) {
      this.refreshView.handletouchmove(event)
    },
    //触摸结束
    handletouchend: function(event) {
      this.refreshView.handletouchend(event)
    },
    //触摸取消
    handletouchcancel: function(event) {
      this.refreshView.handletouchcancel(event)
    },
    //页面滚动
    onPageScroll: function(event) {
      this.refreshView.onPageScroll(event)
    },
  }
})